package br.ufc.apsoo.controllers;

import java.util.List;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Put;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.ufc.apsoo.models.Servico;
import br.ufc.apsoo.repositories.TodosServicos;

@Resource
public class ServicoController {

	private final Result result;

	private final Validator validator;

	private final TodosServicos todosServicos;

	public ServicoController(Result result, Validator validator,
			TodosServicos todosServicos) {
		this.validator = validator;
		this.result = result;
		this.todosServicos = todosServicos;
	}

	@Put
	@Path("/servico")
	public void atualiza(Servico servico) {
		validator.validate(servico);
		validator.onErrorUsePageOf(this).mostra(servico);
		todosServicos.atualiza(servico);
		result.include("message", "Serviço atualizado com sucesso!")
				.redirectTo(this).lista(new Servico());
	}

	@Post
	@Path("/servico/{servico.id}")
	public void desativa(Servico servico) {
		todosServicos.desativaEste(servico);
		result.redirectTo(this).lista(new Servico());
	}

	@Get
	@Path("/servico")
	public void index() {
	}

	@Post
	@Path("/servico")
	public void insere(Servico servico) {
		validator.validate(servico);
		validator.onErrorUsePageOf(this).novo();
		todosServicos.adiciona(servico);
		result.include("message", "Serviço salvo com sucesso!")
				.redirectTo(this).lista(new Servico());
	}

	@Get
	@Path("/servico/lista")
	public List<Servico> lista(Servico servico) {
		return todosServicos.listaPor(servico);
	}

	@Get
	@Path("/servico/mostra/{servico.id}")
	public Servico mostra(Servico servico) {
		return todosServicos.trazPorId(servico.getId());
	}

	@Get
	@Path("/servico/novo")
	public Servico novo() {
		Servico servico = new Servico();
		servico.ativa();
		return servico;
	}
}
